package com.echat.elocation.base;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;

import com.echat.elocation.manager.ActivityCollector;
import com.echat.elocation.callback.PermissionListener;
import com.echat.elocation.R;
import com.echat.elocation.util.Logger;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author lihao
 *
 * @date 2018/7/11 9:42
 */
public abstract class BaseActivity extends AppCompatActivity {

    protected static PermissionListener mListener;
    protected static final int REQUEST_CODE = 1;

    protected String[] permissions = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.MODIFY_AUDIO_SETTINGS,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.CHANGE_WIFI_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        Logger.i("BaseActivity", getClass().getSimpleName());
        ActivityCollector.addActivity(this);
        // 初始化toolbar
        initToolbar();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }

    /**
     * 获取布局
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * 初始化控件
     */
    protected abstract void initView();

    /**
     * 初始化数据
     */
    protected abstract void initData();

    protected void initToolbar(){
        Toolbar toolbar = findViewById(R.id.toolbar);
        if(toolbar != null){
            setSupportActionBar(toolbar);
        }
        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null){
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;

            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    protected void openActivity(Class<?> cls){
        openActivity(this, cls);
    }

    public static void openActivity(Context context, Class<?> cls){
        Intent intent = new Intent(context, cls);
        context.startActivity(intent);
    }

    /**
     * 请求权限
     *
     * @param permissions
     *          需要请求的权限
     * @param listener
     *          请求权限结果回调
     */
    public static void requestPermission(String[] permissions, PermissionListener listener){
        Activity topActivity = ActivityCollector.getTopActivity();
        if(topActivity == null) {
            return;
        }
        mListener = listener;
        List<String> requestPermissionList = new ArrayList<>();
        for(String permission : permissions){
            if(ActivityCompat.checkSelfPermission(topActivity, permission)
                    != PackageManager.PERMISSION_GRANTED){
                requestPermissionList.add(permission);
            }
        }
        if(requestPermissionList.isEmpty()) {
            // 已授权
            mListener.onGranted();
        } else {
            // 有未授权的权限，需请求权限
            ActivityCompat.requestPermissions(topActivity, requestPermissionList.toArray(
                    new String[requestPermissionList.size()]), REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case REQUEST_CODE:
                List<String> deniedPermissionList = new ArrayList<>();
                if(grantResults.length > 0){
                    for(int i = 0; i < grantResults.length; i++){
                        if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
                            deniedPermissionList.add(permissions[i]);
                        }
                    }
                }
                if(deniedPermissionList.isEmpty()) {
                    mListener.onGranted();
                } else {
                    mListener.onDenied(deniedPermissionList);
                }
                break;
            default:
                break;
        }
    }
}
